package com.bupt.cosmfl.cosmflweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bupt.cosmfl.cosmflweb.dto.PageDTO;
import com.bupt.cosmfl.cosmflweb.exception.BusinessException;
import com.bupt.cosmfl.cosmflweb.mapper.NodeGroupMapper;
import com.bupt.cosmfl.cosmflweb.mapper.NodeManageMapper;
import com.bupt.cosmfl.cosmflweb.model.NodeEntity;
import com.bupt.cosmfl.cosmflweb.model.NodeGroupEntity;
import com.bupt.cosmfl.cosmflweb.model.NodeGroupEntityVO;
import com.bupt.cosmfl.cosmflweb.service.NodeGroupService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author fangtiewei
 * @Date 2021/7/28 12:09
 * @Description
 */
@Service
public class NodeGroupServiceImpl implements NodeGroupService {
    @Resource
    private NodeGroupMapper nodeGroupMapper;

    @Resource
    private NodeManageMapper nodeManageMapper;

    @Override
    public IPage<NodeGroupEntityVO> list(PageDTO dto) {
        IPage<NodeGroupEntity> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        QueryWrapper<NodeGroupEntity> wrapper = new QueryWrapper<>();
        if (dto.getKeyword() != null && StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like("name", dto.getKeyword());
        }
        try {
            //查询组
            page = nodeGroupMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            throw new BusinessException("select nodeGroup error: " + e.getMessage());
        }
        List<NodeGroupEntity> groupList = page.getRecords();
        //组视图
        IPage<NodeGroupEntityVO> groupVoList = new Page<>(dto.getPageNum(), dto.getPageSize());
        groupVoList.setRecords(new ArrayList<>());

        if (!CollectionUtils.isEmpty(groupList)) {
            //查询每个组下的nodeList
            for (NodeGroupEntity group : groupList){
                NodeGroupEntityVO newGroupEntityVo = new NodeGroupEntityVO();
                BeanUtils.copyProperties(group, newGroupEntityVo);
                Map<String, Object> query = new HashMap<>();
                query.put("nm_group_id", group.getId());
                try {
                    List<NodeEntity> nodeList = nodeManageMapper.selectByMap(query);
                    newGroupEntityVo.setNodeList(nodeList);
                } catch (Exception e) {
                    throw new BusinessException("select node list in group error:" + e.getMessage());
                }
                groupVoList.getRecords().add(newGroupEntityVo);
            }
        }
        groupVoList.setTotal(page.getTotal());
        return groupVoList;
    }
}
